package com.persia.handler;

import com.persia.exception.ViewException;
import freemarker.core.Environment;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.Writer;

/**
 * freemarker页面上的异常控制
 * 在template factory里头设置
 * @author caibosi
 * @created 2014-02-01
 */
public class FreemarkerExceptionHandler implements TemplateExceptionHandler {
    private static final Logger log = Logger
            .getLogger(FreemarkerExceptionHandler.class);

    public void handleTemplateException(TemplateException te, Environment env,
                                        Writer out) throws TemplateException {
        try {
            out.write("[Error: " + te.getMessage() + "]");
            log.warn("[Freemarker Error: " + te.getMessage() + "]");
            throw new ViewException("freemarker error",te);
        } catch (IOException e) {
            log.warn(e.getMessage());
            throw new TemplateException(
                    "Failed to print error message. Cause: " + e, env);
        }
    }
}
